<template>
  <div class="min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <nav class="bg-emerald-600 text-white shadow-md">
      <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
          <i class="fas fa-leaf text-2xl"></i>
          <span class="text-xl font-bold">营养师后台管理系统</span>
        </div>
        <div class="flex items-center space-x-4">
          <a href="#" class="hover:text-emerald-200">
            <i class="fas fa-bell"></i>
            <span class="bg-red-500 text-white rounded-full w-5 h-5 text-xs flex items-center justify-center absolute -mt-8 ml-3">3</span>
          </a>
          <div class="relative group">
            <div class="flex items-center space-x-2 cursor-pointer">
              <img src="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=150&h=150&q=80"
                class="w-8 h-8 rounded-full object-cover" alt="用户头像">
              <span>管理员</span>
              <i class="fas fa-chevron-down text-xs"></i>
            </div>
            <div class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 hidden group-hover:block">
              <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                <i class="fas fa-user mr-2"></i>个人信息
              </a>
              <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                <i class="fas fa-cog mr-2"></i>系统设置
              </a>
              <div class="border-t border-gray-200 my-1"></div>
              <a href="#" @click.prevent="logout" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
              </a>
            </div>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容区 -->
    <div class="flex flex-1">
      <!-- 侧边导航 -->
      <SideNav />

      <!-- 主内容 -->
      <main class="flex-1 p-6">
        <div class="mb-6">
          <h1 class="text-2xl font-bold text-gray-800">仪表盘</h1>
          <p class="text-gray-600">欢迎回来，管理员！这是您的实时数据概览。</p>
        </div>

        <!-- 数据卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-gray-500">用户总数</p>
                <h3 class="text-3xl font-bold text-gray-800">2,563</h3>
              </div>
              <div class="bg-emerald-100 rounded-full w-12 h-12 flex items-center justify-center">
                <i class="fas fa-users text-emerald-600 text-xl"></i>
              </div>
            </div>
            <p class="mt-4 text-green-600"><i class="fas fa-arrow-up mr-1"></i> 8.2% <span class="text-gray-500">本周增加</span></p>
          </div>

          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-gray-500">食物数据</p>
                <h3 class="text-3xl font-bold text-gray-800">1,128</h3>
              </div>
              <div class="bg-blue-100 rounded-full w-12 h-12 flex items-center justify-center">
                <i class="fas fa-apple-alt text-blue-600 text-xl"></i>
              </div>
            </div>
            <p class="mt-4 text-green-600"><i class="fas fa-arrow-up mr-1"></i> 3.1% <span class="text-gray-500">本月增加</span></p>
          </div>

          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-gray-500">食谱总数</p>
                <h3 class="text-3xl font-bold text-gray-800">437</h3>
              </div>
              <div class="bg-purple-100 rounded-full w-12 h-12 flex items-center justify-center">
                <i class="fas fa-utensils text-purple-600 text-xl"></i>
              </div>
            </div>
            <p class="mt-4 text-green-600"><i class="fas fa-arrow-up mr-1"></i> 12.4% <span class="text-gray-500">本月增加</span></p>
          </div>

          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-gray-500">今日饮食记录</p>
                <h3 class="text-3xl font-bold text-gray-800">872</h3>
              </div>
              <div class="bg-amber-100 rounded-full w-12 h-12 flex items-center justify-center">
                <i class="fas fa-clipboard-list text-amber-600 text-xl"></i>
              </div>
            </div>
            <p class="mt-4 text-red-600"><i class="fas fa-arrow-down mr-1"></i> 2.5% <span class="text-gray-500">昨日对比</span></p>
          </div>
        </div>

        <!-- 图表和统计 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <!-- 用户活跃度趋势 -->
          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between mb-4">
              <h4 class="text-lg font-medium text-gray-800">用户活跃度趋势</h4>
              <div class="flex items-center space-x-2">
                <select class="border rounded-md px-2 py-1 text-sm" v-model="activityPeriod">
                  <option value="7">过去7天</option>
                  <option value="30">过去30天</option>
                  <option value="90">过去90天</option>
                </select>
              </div>
            </div>
            <div ref="activityChartRef" class="h-64"></div>
          </div>

          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between mb-4">
              <h4 class="text-lg font-medium text-gray-800">平均营养素摄入分布</h4>
              <div class="flex items-center space-x-2">
                <select class="border rounded-md px-2 py-1 text-sm" v-model="nutrientPeriod">
                  <option value="week">本周</option>
                  <option value="month">本月</option>
                  <option value="year">全年</option>
                </select>
              </div>
            </div>
            <div ref="nutrientChartRef" class="h-64"></div>
            <div class="mt-4 flex justify-around">
                <div class="flex items-center">
                    <div class="w-3 h-3 bg-emerald-500 rounded-full mr-2"></div>
                    <span class="text-xs">蛋白质 (30%)</span>
                </div>
                <div class="flex items-center">
                    <div class="w-3 h-3 bg-amber-500 rounded-full mr-2"></div>
                    <span class="text-xs">脂肪 (25%)</span>
                </div>
                <div class="flex items-center">
                    <div class="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
                    <span class="text-xs">碳水化合物 (45%)</span>
                </div>
            </div>
          </div>
        </div>

        <!-- 最近活动和热门食谱 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 最近活动 -->
          <div class="bg-white rounded-lg shadow-md p-6">
            <h4 class="text-lg font-medium text-gray-800 mb-4">最近活动</h4>
            <div class="space-y-4">
              <div v-for="(activity, index) in recentActivities" :key="index">
                <div class="flex">
                  <div class="flex-shrink-0 mr-3">
                    <div class="w-10 h-10 rounded-full flex items-center justify-center" :class="activity.bgColor">
                      <i class="fas" :class="[activity.icon, activity.iconColor]"></i>
                    </div>
                  </div>
                  <div>
                    <p class="text-gray-800">{{ activity.title }}</p>
                    <p class="text-gray-500 text-sm">{{ activity.description }}</p>
                    <p class="text-gray-400 text-xs mt-1">{{ activity.time }}</p>
                  </div>
                </div>
                <div v-if="index < recentActivities.length - 1" class="border-t border-gray-100 mt-4"></div>
              </div>
            </div>
          </div>


          <!-- 热门食谱 -->
          <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center justify-between mb-4">
              <h4 class="text-lg font-medium text-gray-800">热门食谱</h4>
              <a href="#" class="text-emerald-600 hover:text-emerald-700 text-sm">查看全部</a>
            </div>
            <div class="space-y-4">
              <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-md hover:shadow-sm transition-shadow">
                <img src="https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=200&h=150&q=80"
                  class="w-16 h-12 rounded-md object-cover" alt="食谱图片">
                <div>
                  <h5 class="text-gray-800 font-medium">健康沙拉碗</h5>
                  <div class="flex items-center mt-1">
                    <i class="fas fa-star text-yellow-400 text-sm"></i>
                    <span class="text-gray-500 text-sm ml-1">4.8</span>
                    <span class="text-gray-500 text-sm ml-2">(123条评价)</span>
                  </div>
                  <p class="text-gray-500 text-sm mt-1">浏览量: 2,580</p>
                </div>
              </div>
              <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-md hover:shadow-sm transition-shadow">
                <img src="https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=200&h=150&q=80"
                  class="w-16 h-12 rounded-md object-cover" alt="食谱图片">
                <div>
                  <h5 class="text-gray-800 font-medium">香烤鸡胸肉</h5>
                  <div class="flex items-center mt-1">
                    <i class="fas fa-star text-yellow-400 text-sm"></i>
                    <span class="text-gray-500 text-sm ml-1">4.5</span>
                    <span class="text-gray-500 text-sm ml-2">(98条评价)</span>
                  </div>
                  <p class="text-gray-500 text-sm mt-1">浏览量: 1,870</p>
                </div>
              </div>
              <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-md hover:shadow-sm transition-shadow">
                <img src="https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=200&h=150&q=80"
                  class="w-16 h-12 rounded-md object-cover" alt="食谱图片">
                <div>
                  <h5 class="text-gray-800 font-medium">能量早餐燕麦粥</h5>
                  <div class="flex items-center mt-1">
                    <i class="fas fa-star text-yellow-400 text-sm"></i>
                    <span class="text-gray-500 text-sm ml-1">4.2</span>
                    <span class="text-gray-500 text-sm ml-2">(76条评价)</span>
                  </div>
                  <p class="text-gray-500 text-sm mt-1">浏览量: 1,495</p>
                </div>
              </div>
            </div>
            <div class="mt-4 text-center">
              <a href="#" class="text-emerald-600 hover:text-emerald-700 text-sm font-medium">查看所有热门食谱</a>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import SideNav from '@/components/SideNav.vue';
import axios from '@/utils/axios-config';

const router = useRouter();
const authStore = useAuthStore();

const logout = () => {
  authStore.logout();
  router.push('/login');
};

const activityChartRef = ref(null);
const nutrientChartRef = ref(null);
let myActivityChart = null;
let myNutrientChart = null;

const activityPeriod = ref('7');
const nutrientPeriod = ref('week');

const recentActivities = ref([
  {
    title: '新用户注册',
    description: '张小明刚刚注册了账号',
    time: '2分钟前',
    icon: 'fa-user-plus',
    bgColor: 'bg-green-100',
    iconColor: 'text-green-600'
  },
  {
    title: '新食谱发布',
    description: '管理员发布了"低脂香煎鸡胸肉"食谱',
    time: '35分钟前',
    icon: 'fa-utensils',
    bgColor: 'bg-blue-100',
    iconColor: 'text-blue-600'
  },
  {
    title: '食物数据更新',
    description: '更新了15种食物的营养数据',
    time: '1小时前',
    icon: 'fa-star',
    bgColor: 'bg-amber-100',
    iconColor: 'text-amber-600'
  },
  {
    title: '系统维护完成',
    description: '系统例行维护和性能优化已完成',
    time: '2小时前',
    icon: 'fa-clipboard-check',
    bgColor: 'bg-purple-100',
    iconColor: 'text-purple-600'
  }
]);

const initActivityChart = () => {
  if (activityChartRef.value) {
    myActivityChart = echarts.init(activityChartRef.value);
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '活跃度',
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
          itemStyle: {
            color: '#34D399' // Tailwind emerald-500
          },
          barWidth: '40%'
        }
      ]
    };
    myActivityChart.setOption(option);
  }
};

const initNutrientChart = () => {
  if (nutrientChartRef.value) {
    myNutrientChart = echarts.init(nutrientChartRef.value);
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        show: false // Legend is displayed outside the chart as per UI
      },
      series: [
        {
          name: '营养素摄入',
          type: 'pie',
          radius: ['70%', '90%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 30, name: '蛋白质', itemStyle: { color: '#10B981' } }, // Tailwind emerald-600
            { value: 25, name: '脂肪', itemStyle: { color: '#F59E0B' } },    // Tailwind amber-500
            { value: 45, name: '碳水化合物', itemStyle: { color: '#3B82F6' } } // Tailwind blue-500
          ]
        }
      ]
    };
    myNutrientChart.setOption(option);
  }
};

watch(activityPeriod, (newValue) => {
  if (!myActivityChart) return;
  let newData;
  let xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']; // Default for 7 days
  if (newValue === '7') {
    newData = [120, 200, 150, 80, 70, 110, 130];
  } else if (newValue === '30') {
    // Simulate 4 weeks of data, aggregated to 7 points for simplicity or show daily for 30 days
    xAxisData = Array.from({length: 30}, (_, i) => `第${i+1}天`);
    newData = Array.from({length: 30}, () => Math.floor(Math.random() * 200) + 50);
  } else { // 90 days
    xAxisData = Array.from({length: 90}, (_, i) => `第${i+1}天`);
    newData = Array.from({length: 90}, () => Math.floor(Math.random() * 300) + 50);
  }
  myActivityChart.setOption({
    xAxis: {
        data: xAxisData
      },
    series: [{ data: newData }]
  });
});

watch(nutrientPeriod, (newValue) => {
  if (!myNutrientChart) return;
  let newData;
  if (newValue === 'week') {
    newData = [
      { value: 30, name: '蛋白质', itemStyle: { color: '#10B981' } },
      { value: 25, name: '脂肪', itemStyle: { color: '#F59E0B' } },
      { value: 45, name: '碳水化合物', itemStyle: { color: '#3B82F6' } }
    ];
  } else if (newValue === 'month') {
    newData = [
      { value: 35, name: '蛋白质', itemStyle: { color: '#10B981' } },
      { value: 30, name: '脂肪', itemStyle: { color: '#F59E0B' } },
      { value: 35, name: '碳水化合物', itemStyle: { color: '#3B82F6' } }
    ];
  } else { // year
    newData = [
      { value: 28, name: '蛋白质', itemStyle: { color: '#10B981' } },
      { value: 22, name: '脂肪', itemStyle: { color: '#F59E0B' } },
      { value: 50, name: '碳水化合物', itemStyle: { color: '#3B82F6' } }
    ];
  }
  myNutrientChart.setOption({
    series: [{ data: newData }]
  });
});

const resizeCharts = () => {
  myActivityChart?.resize();
  myNutrientChart?.resize();
};

onMounted(async () => {
  await nextTick(); 
  initActivityChart();
  initNutrientChart();
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  myActivityChart?.dispose();
  myNutrientChart?.dispose();
});

// FontAwesome and TailwindCSS are expected to be globally available
// If not, they should be imported or linked in main.js or index.html of the Vue project.
</script>

<style scoped>
/* Scoped styles for DashboardView */
/* Tailwind CSS classes are used directly in the template */
</style>